import { isArray, cloneDeep } from "lodash";
import config from "@/config.mjs";
import storage from "@/utils/storage";

// 链接过滤
function urlFilter(str, status = 1, type) {
  let _href = `${config.LOCATION_ORIGIN}/customer/common/image/getRealImageUrl?realUrl=`;
  if (type == 'test') {
    _href =
      'https://csolutionc.timepivot.cn/customer/common/image/getRealImageUrl?realUrl=';
  }
  const key = '?realUrl=';
  if (str) {
    if (str.indexOf('https://thirdwx.qlogo.cn') !== -1) {
      return str;
    }
    if (str.indexOf('clife-ai-cv-face-age-edit') !== -1) {
      return str;
    }
    const start = str.indexOf(key);
    if (start !== -1) {
      str = str.substring(start);
      str = str.replace(key, '');
    }
    if (status === 1) str = `${_href}${str}`;
    if (status === 2)
      str = `${_href}${str}&realParam=image/resize,w_300/quality,q_70`;
    return str;
  }
  return '';
}

function scan() {
  uni.scanCode({
    success: (res) => {
      console.log(res.path);
      if (res.path) {
        uni.navigateTo({
          url: `/${res.path}`,
          fail: () => {
            uni.reLaunch({
              url: `/${res.path}`,
              fail: () => {
                uni.showToast({
                  icon: 'none',
                  title: '路径错误，请联系管理员',
                });
              },
            });
          },
        });
      }
    },
    fail: (res) => {
      console.log(res);
      if (res.errMsg !== 'scanCode:fail cancel') {
        uni.$u.toast('识别错误');
      }
    },
  });
}

/**
 * 自动获取地址
 * @param {String} url 地址
 */
function url(url, isImage = true) {
  // 正式用这个
  const LOCATION_ORIGIN = `${
    config.LOCATION_ORIGIN
  }/customer/common/image/getRealImageUrl?realUrl=${
    config.WECHAT_APPID + config.VERSION_NUMBER
  }`;
  // const LOCATION_ORIGIN = '/static';
  const realUrl = `${LOCATION_ORIGIN}${isImage ? "/images" : ""}${url}`;
  return realUrl;
}

/**
 * 图片处理-预览图片
 * @param {Array} urls - 图片列表
 * @param {Number} current - 首个预览下标
 */
function previewImage(urls = [], current = 0) {
  urls = urls.map((v) => urlFilter(v));
  uni.previewImage({
    urls,
    current,
    indicator: 'default',
    loop: true,
    fail(err) {
      console.log('previewImage出错', urls, err);
    },
  });
}

// 跳转综合搜索

// rpx转px
function rpxToPx(rpx) {
  const { screenWidth } = uni.getSystemInfoSync();
  return (screenWidth * Number.parseInt(rpx)) / 750;
}

// px转rpx
function pxToRpx(px) {
  const { screenWidth } = uni.getSystemInfoSync();
  return (750 * Number.parseInt(px)) / screenWidth;
}
// 根据指定页面，跳转到指定页
function backPage(path, params) {
  const pages = getCurrentPages(); // 获取栈实例
  const prevPage = pages[pages.length - 2]; // 获取上个页面的数据，包含页面路由
  if (prevPage?.route === path) {
    uni.navigateBack();
  } else {
    uni.navigateTo({
      url: `/${path}${params}`,
    });
  }
}

function back() {
  const routes = getCurrentPages();
  if (routes.length <= 1) {
    uni.switchTab({
      url: '/pages/index/index',
    });
  } else {
    uni.navigateBack();
  }
}

function jsGetAge(strBirthday) {
  let returnAge;
  // 根据生日计算年龄
  // 以下五行是为了获取出生年月日，如果是从身份证上获取需要稍微改变一下
  const strBirthdayArr = strBirthday.split('-');
  const birthYear = strBirthdayArr[0];
  const birthMonth = strBirthdayArr[1];
  const birthDay = strBirthdayArr[2];

  const d = new Date();
  const nowYear = d.getFullYear();
  const nowMonth = d.getMonth() + 1;
  const nowDay = d.getDate();

  if (nowYear == birthYear) {
    returnAge = 0; // 同年 则为0岁
  } else {
    const ageDiff = nowYear - birthYear; // 年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        const dayDiff = nowDay - birthDay; // 日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      } else {
        const monthDiff = nowMonth - birthMonth; // 月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      }
    } else {
      returnAge = -1; // 返回-1 表示出生日期输入错误 晚于今天
    }
  }

  return returnAge; // 返回周岁年龄
}

/**
 * 获取微信授权
 * @param {String} scope 需要获取的权限（参考https://uniapp.dcloud.io/api/other/authorize）
 * @tutorial https://uniapp.dcloud.io/api/other/authorize
 * @param {String} tips  给用户的提示信息
 * @param {String} title  弹窗标题
 */
function getAuthorize(
  scope = 'scope.userLocation',
  tips = '为了更好的服务，请允许我们获取您的位置信息',
  title = '温馨提示'
) {
  return new Promise((resolve) => {
    if (scope) {
      uni.authorize({
        scope,
        success: (res) => {
          resolve(true);
        },
        fail: (res) => {
          uni.showModal({
            title,
            content: tips,
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({
                  success: (result) => {
                    resolve(result.authSetting[scope]);
                  },
                });
              } else {
                resolve(false);
              }
            },
          });
        },
      });
    } else {
      console.error('请传入正确的授权码');
      resolve(false);
    }
  });
}
// 解析rpx
export function parseRpx(val) {
  return isArray(val) ? val.map(parseRpx).join(' ') : `${parseFloat(val)}rpx`;
}
// 获取元素位置信息
export async function getRect(selector, proxy) {
  return new Promise((resolve) => {
    uni
      .createSelectorQuery()
      .in(proxy)
      .select(selector)
      .boundingClientRect((res) => {
        resolve(res);
      })
      .exec();
  });
}
// uuid
export function uuid() {
  const s = [];
  const hexDigits = '0123456789abcdef';
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = '4';
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23] = '-';

  return s.join('');
}

export function msg(title, callback = null) {
  uni.showToast({
    icon: 'none',
    title,
    success: callback,
  });
}
export function showTips(text) {
  uni.showModal({
    title: '温馨提示',
    content: text,
    showCancel: false,
    confirmText: '知道了',
  });
}

export default {
  storage,
  showTips,
  url,
  getRect,
  parseRpx,
  scan,
  urlFilter,
  previewImage,
  jsGetAge,
  rpxToPx,
  pxToRpx,
  msg,
  back,
  backPage,
  getAuthorize,
  cloneDeep,
};
